<?php
// +----------------------------------------------------------------------
// | 知识星球[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 abcblockchain.io
// +----------------------------------------------------------------------
// | 后台管理使用了HisiPHP
// +----------------------------------------------------------------------
// | Author: abcblockchain.io
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 点赞模型
 * @package app\common\model
 */
class Likes extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'ctime';
    protected $updateTime = false;

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    /**
     * 点赞
     * @author
     * @param $postId
     * @param $userId
     * @return bool
     */
    public function createLikes($postId, $userId)
    {
        $map = [];
        $map['likeable_id'] = $postId;
        $map['user_id'] = $userId;
        $map['likeable_type'] = 1;
        $isHave = $this->where($map)->field('id')->find();
        if ($isHave) {
            $save['status'] = 1;
            $res = $this->where($map)->update($save);
        } else {
            $res = $this->validate('Likes.create')->isUpdate(false)->save($map);
        }
        if ($res === false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 取消赞
     * @author
     * @param $postId
     * @param $userId
     * @return bool
     */
    public function cancelLikes($postId, $userId)
    {
        $map = [];
        $map['likeable_id'] = $postId;
        $map['user_id'] = $userId;
        $map['likeable_type'] = 1;
        $save['status'] = 0;
        $res = $this->where($map)->update($save);
        if ($res === false) {
            return false;
        } else {
            return true;
        }
    }

}